package common

import (
	"os"
	"path/filepath"
	"time"

	"github.com/spf13/viper"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

// 导出实例
func Logger() *zap.SugaredLogger {
	logMode := zapcore.DebugLevel
	if !viper.GetBool("service.dev") {
		logMode = zapcore.InfoLevel
	}
	core := zapcore.NewCore(getEncoder(), zapcore.NewMultiWriteSyncer(getWriteConfig(), zapcore.AddSync(os.Stdout)), logMode)
	return zap.New(core).Sugar()
}

// 返回自定义配置
func getEncoder() zapcore.Encoder {
	encodeConfig := zap.NewProductionEncoderConfig()
	encodeConfig.TimeKey = "time"
	// 变成大写
	encodeConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	// 修改时间格式
	encodeConfig.EncodeTime = func(t time.Time, encoder zapcore.PrimitiveArrayEncoder) {
		encoder.AppendString(t.Local().Format(time.DateTime))
	}

	return zapcore.NewJSONEncoder(encodeConfig)
}

// 写入本地配置
func getWriteConfig() zapcore.WriteSyncer {
	// 创建路径
	// 分割符号
	seperator := string(filepath.Separator)
	// 目录
	writeDir, _ := os.Getwd()
	// 拼接路径  + 文件名 + 格式
	fullPath := writeDir + seperator + "log" + seperator + time.Now().Format(time.DateOnly) + ".txt"

	// 大小与保存时间设置 lumberjack
	wirteConfig := &lumberjack.Logger{
		Filename:   fullPath,
		MaxSize:    viper.GetInt("logger.MaxSize"),    //文件最大MB
		MaxBackups: viper.GetInt("logger.MaxBackups"), //保存份数
		MaxAge:     viper.GetInt("logger.MaxAge"),     //保存天数
		Compress:   viper.GetBool("logger.Compress"),  //是否在压缩
	}
	return zapcore.AddSync(wirteConfig)
}
